<template>
  <div class="home-container">
    <search-bar />
    <!-- 加载失败 -->
    <empty v-if="error" :description="errorMsg" @tap="getList" />
    <!-- 正在加载 -->
    <empty v-else-if="loading" image-type="default" description="正在拼命加载" :show-button="false" />
    <!-- 正文 -->
    <tabs v-else sticky offset-top="1.22667rem">
      <van-tab title="正在热映">
        <div class="film-wrap">
          <film-card v-for="hot in hotFilmList" :key="hot.filmId" :film="hot" />
        </div>
      </van-tab>
      <van-tab title="即将上映">
        <div class="film-wrap">
          <film-card v-for="soon in soonFilmList" :key="soon.filmId" :film="soon" />
        </div>
      </van-tab>
    </tabs>
  </div>
</template>

<script>
import SearchBar from '@/components/SearchBar'
import Tabs from '@/components/Tabs'
import FilmCard from '@/components/FilmCard'
import { mapGetters } from 'vuex'

export default {
  name: "HomePage",
  components: { SearchBar, Tabs, FilmCard },
  computed: {
    ...mapGetters([
      'hotFilmList', 
      'soonFilmList',
      'currentCity'
    ])
  },
  watch: {
    async currentCity(newCity, oldCity) {
      // oldCity 为 null，表示第一次改变（created时），所以不加载
      if (oldCity !== null) {
        this.$toast.loading('正在更新')
        const allList = await this.$store.dispatch('film/getFilmList')
        this.$notify({
          type: 'success',
          message: `为您推荐${allList.length}条影片`
        })
        this.$toast.clear()
      }
    }
  },
  data() {
    return {
      error: false,
      errorMsg: '数据加载失败',
      loading: true,
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      try {
        this.error = false
        this.loading = true
        if (!this.currentCity) {
          await this.$store.dispatch('city/getCurrentCity')
        }
        await this.$store.dispatch('film/getFilmList')
      } catch (error) {
        this.error = true
        this.errorMsg = error.message
      } finally {
        this.loading = false
      }
    }
  },
};
</script>

<style lang="scss" scoped>
.home-container {
  .film-wrap {
    padding: 10px 0;
  }
}
</style>
